package com.tueye.web.controller.publishtopic;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tueye.ajax.json.JSONException;
import com.tueye.ajax.json.JSONObject;
import com.tueye.base.util.Page;
import com.tueye.entity.Comment;
import com.tueye.entity.Pictures;
import com.tueye.entity.Topics;
import com.tueye.entity.user.User;
import com.tueye.service.ITopicService;
import com.tueye.service.exception.TuEyeServiceException;
import com.tueye.service.usermanager.IUserDynamicService;
import com.tueye.utils.CreateHtmlUtil;
import com.tueye.utils.DateUtils;
import com.tueye.utils.FileHandle;
import com.tueye.utils.HtmlConverseUtil;
import com.tueye.utils.TuEyeConstant;
import com.tueye.utils.UUIDGenerator;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;



/**
 *  Title: UploadFileController.java
 *  Description: upload the imagess.
 * @author yuyue
 * @version 0.5 (for test)
 * 
 */
@SuppressWarnings("unchecked")
@Controller
public class ShowTopicController {

	Log log = LogFactory.getLog(ShowTopicController.class);
	String file_spe = File.separator;
	@Autowired
	@Qualifier("topicService")
	ITopicService topicService;

	@Autowired
	@Qualifier("userDynamicService")
	IUserDynamicService userDynamicService;
	
	@RequestMapping("/createList.do") 
	public void createTypeList(HttpServletRequest request, HttpServletResponse response){ 
	//拿到tueye cache 里面所有的type
	String retult = "true";
	try{
	 	String id = request.getParameter("tid");
	 	Topics topic = topicService.getTopicById(id);
	 	
		//查一次，知道有多少页，生成index.html
		 
		String hql = "from Pictures t where  t.topics.id = '"+ topic.getId() + "'";
		Page page = topicService.pagedQueryByHQL(hql, 1, 3, null);
		String htmlFileName = TuEyeConstant.PROJECTPATH + topic.getTopic_type().getType_enlish_name() + file_spe +topic.getTopic_code() + file_spe + "index.html"; 
		FileHandle.checkIsADirectory(TuEyeConstant.PROJECTPATH + topic.getTopic_type().getType_enlish_name() + file_spe +topic.getTopic_code());
		
		String templatePath = TuEyeConstant.PROJECTPATH +file_spe+"WEB-INF"+ file_spe + "views"+file_spe+"v1.0";
		Configuration cfg = null;
		cfg = new Configuration();
		cfg.setDefaultEncoding("utf-8"); 
		cfg.setDirectoryForTemplateLoading(new File(templatePath));
		cfg.setObjectWrapper(new DefaultObjectWrapper()); 
		Template temp = cfg.getTemplate("final.ftl");
		// add by shiwei
		String articleTopicId = "" ; 
		if(topic.getArticleTopic() != null)
			articleTopicId = topic.getArticleTopic().getId();
		
		HashMap contents = new HashMap();
		// add by shiwei 
		contents.put("articleTopicId",articleTopicId);
		contents.put("title",StringUtils.isEmpty(topic.getTopic_title())?"TuEye列表首页":topic.getTopic_title());
		contents.put("keyword", StringUtils.isEmpty(topic.getKeywords())?"Tueye 图文并茂":"");
		contents.put("description", StringUtils.isEmpty(topic.getTopic_description())?"tueye 图文并茂":topic.getTopic_description());
		contents.put("pagetitle", StringUtils.isEmpty(topic.getTopic_title())?"tueye 图文并茂":topic.getTopic_title());
		contents.put("countnum", topicService.getClickNumByTopicId(id) );
		contents.put("time",  DateUtils.getDate2Str("yyyy-MM-dd HH:mm",topic.getSys_time()));
		contents.put("todayUNum","20");
		contents.put("author", StringUtils.isEmpty(topic.getTopic_author())?"tueye编辑":"<a href='../../userblog.do?userid="+getUserIdByTopic(topic)+"' target='_blank'>" + topic.getTopic_author() + "</a>");
		contents.put("overview", StringUtils.isEmpty(topic.getTopic_overview())?"tueye编辑":topic.getTopic_overview());
		contents.put("contenttilte", StringUtils.isEmpty(topic.getTopic_title())?"啥也别说了，使劲看吧！":topic.getTopic_title());
		contents.put("showmain", getContent(page));
		contents.put("pagenum", CreateHtmlUtil.getPageNum(page.getCurrentPageNo(), page.getTotalPageCount(),String.valueOf(topic.getTopic_code())));
		contents.put("topicid",topic.getId());
		contents.put("xiangguan",getXiangGuan(topic));
		contents.put("topicidforflower",topic.getId());
		contents.put("daohang",getDaoHang(topic));
		contents.put("upnext",getUpNextPage(topic));
		contents.put("top15", getTop15());
		Map<String, Object> map = topicService.getDingOrCaiNum(id);
		contents.put("dingyixia", map.get("flowersNum"));
		contents.put("caiyixia", map.get("caiNum"));
		Writer out = new OutputStreamWriter(new FileOutputStream(htmlFileName),"utf-8");
		temp.process(contents, out);
		out.flush();
		out.close();
			
		//循环生成其他页
		for(int i = 2; i<= page.getTotalPageCount(); i++)
		{
		
			Page page_temp = topicService.pagedQueryByHQL(hql, i, 3, null);
			String htmlFileName_temp = TuEyeConstant.PROJECTPATH + topic.getTopic_type().getType_enlish_name() + file_spe +topic.getTopic_code() + file_spe +topic.getTopic_code() + "_"+i+".html"; 
			   
			contents.put("showmain", getContent(page_temp));
			contents.put("pagenum", CreateHtmlUtil.getPageNum(page_temp.getCurrentPageNo(), page_temp.getTotalPageCount(),String.valueOf(topic.getTopic_code())));
			 
			 Writer out_temp = new OutputStreamWriter(new FileOutputStream(htmlFileName_temp),"utf-8");
			 temp.process(contents, out_temp);
			 out_temp.flush();
			 out_temp.close();
			 
		} 
		//判断是否把topic的发布类型改成发布，如果没有就改，然后记录到网站动态里面
		if(topic.getTopic_release_type() == 0)
		{
			topic.setTopic_release_type(1);
			topicService.updateTopic(topic);
		}
		
		response.getWriter().print("true");
	}catch (Exception e) {
		e.printStackTrace();
	} 
    
}

private String getTodayUpdateConut() throws TuEyeServiceException{
	String hql = "from Topics t where" +
			" to_date(to_char("+DateUtils.getCurrentTimestamp()+", 'yyyy-MM-dd'), 'yyyy-mm-dd')" +
			" = to_date(to_char(t.sys_time, 'yyyy-MM-dd'), 'yyyy-mm-dd')";
	List<Topics> topics = topicService.getTopicsByHql(hql);
	String count = String.valueOf(topics.size());
	return count;
}
//设置主体内容
private String getContent(Page page){
	
	 List<Pictures> pictures =  (List<Pictures>) page.getResult();
	 StringBuffer sb = new StringBuffer();
	 
	 for(Iterator iter = pictures.iterator() ; iter.hasNext();){
		 Pictures picture = (Pictures) iter.next();
		 sb.append("<li><img src=\""+picture.getPicture_url()+"\" onload=\"javascript:DrawImage(this,640,528)\" onclick=\"Pop(this,50,'PopBoxImageLarge');\" class=\"PopBoxImageLarge\"  title=\""+picture.getPicture_name()+"\" alt=\""+picture.getPicture_name()+"\"/></li>");
		 sb.append("<li>").append(picture.getPicture_description()).append("</li>");
	 }
	return sb.toString();
}

private int getCommonts(Pictures picture){
	if(picture != null &&picture.getComments()!=null )
		return picture.getComments().size();
	else
		return 0;
}
//加载留言
@RequestMapping("/loadcomments.do") 
public String loadComments(HttpServletRequest request, HttpServletResponse response) throws TuEyeServiceException, IOException, TemplateException, JSONException{ 
	//拿到tueye cache 里面所有的type
	String id = request.getParameter("pid");
	List<Comment> comments = topicService.getAllCommentsByPId(id);
	 
	 List mapList = new ArrayList();   
	int i = 0;
	for(Iterator iter = comments.iterator(); iter.hasNext();){
		Comment comment = (Comment) iter.next();
		Map cellMap = new HashMap();
		cellMap.put("lou", i+1);
		cellMap.put("comment", new Object[]{ 
				replaceBianqing(comment.getCommentcontent()), 
				comment.getCommentusername(),
				getUserPoto(comment.getUser().getUserPoto()),
				DateUtils.getDate2Str("yyyy-MM-dd HH:mm",comment.getSys_time())
				});
				mapList.add(cellMap);
				i++;
				
	}
	Map  map = new HashMap();
	map.put("comments", mapList);
	JSONObject object = new JSONObject(map);
	response.setContentType("html/text");
	response.setCharacterEncoding("utf-8");
	response.getWriter().println(object.toString());
	System.out.println(object.toString());
	return null;
}


@RequestMapping("/publiscomments.do") 
public String publishComments(HttpServletRequest request, HttpServletResponse response) throws TuEyeServiceException, IOException, TemplateException, JSONException{ 
	//拿到tueye cache 里面所有的type
	response.setContentType("html/text");
	response.setCharacterEncoding("utf-8");
	String pid = request.getParameter("picturid");
	String commenttext = HtmlConverseUtil.getInstance().encode(request.getParameter("commenttext"));
	User user = (User) request.getSession().getAttribute(TuEyeConstant.TUEYE_USER);
	 if(user == null)
	 {
		 response.getWriter().println("s=2");
		 return null;
	 }
	 
	 Pictures picture = topicService.getPictureById(pid);
	 Comment comment = new Comment();
	 comment.setCommentcontent(commenttext);
	 comment.setPicture(picture);
	 comment.setId(UUIDGenerator.getUUID());
	 comment.setCommentusername(user.getByname());
	 comment.setUser(user);
	 comment.setSys_time(DateUtils.getCurrentDate());
	 topicService.saveComment(comment);
	 
	
	response.getWriter().println("s=1");
	 
	return null;
}

@RequestMapping("/getClickNum.do") 
public String getClickNum(HttpServletRequest request, HttpServletResponse response) {
	String topicid = request.getParameter("topicid");
	
	try {
		String clickNum = topicService.getClickNumByTopicId(topicid);
		response.getWriter().println(clickNum);
	} catch (Exception e) {
		e.printStackTrace();
	}
	
	return null;
}



public String getUserPoto(String userpoto){
	if(userpoto == null || "".equals(userpoto))
	{
		
		return "userphoto.jpg";
	}else 
	{
		return userpoto;
	}
}
 public String replaceBianqing(String commentText){
	 commentText = commentText.replaceAll(":bishi:", "<img src=\"../../themes/images/biaoqing/1.gif\" />")
	 				.replaceAll(":chongbai:", "<img src=\"../../themes/images/biaoqing/2.gif\" />")
	 				.replaceAll(":bucuo:", "<img src=\"../../themes/images/biaoqing/3.gif\" />")
	 				.replaceAll(":bixue:", "<img src=\"../../themes/images/biaoqing/4.gif\" />")
	 				.replaceAll(":naoni:", "<img src=\"../../themes/images/biaoqing/5.gif\" />")
	 				.replaceAll(":dise:", "<img src=\"../../themes/images/biaoqing/6.gif\" />")
	 				.replaceAll(":chaoxiao:", "<img src=\"../../themes/images/biaoqing/7.gif\" />")
	 				.replaceAll(":buzhidao:", "<img src=\"../../themes/images/biaoqing/8.gif\" />")
	 				.replaceAll(":kun:", "<img src=\"../../themes/images/biaoqing/9.gif\" />")
	 				.replaceAll(":meideheng:", "<img src=\"../../themes/images/biaoqing/10.gif\" />")
	 				.replaceAll(":weiqu:", "<img src=\"../../themes/images/biaoqing/11.gif\" />")
	 				.replaceAll(":daxiao:", "<img src=\"../../themes/images/biaoqing/12.gif\" />")
	 				.replaceAll(":daizi:", "<img src=\"../../themes/images/biaoqing/13.gif\" />")
	 				.replaceAll(":youzai:", "<img src=\"../../themes/images/biaoqing/14.gif\" />")
	 				.replaceAll(":paomeiyan:", "<img src=\"../../themes/images/biaoqing/15.gif\" />")
	 				;
	 return commentText;
 }
 
 private String getUserIdByTopic(Topics topic){
	return  topicService.getUserByTopic(topic).getId();
 }
 
 private String getXiangGuan(Topics topic) throws TuEyeServiceException{
	 String hql = "from Topics t where  t.keywords like '%"+ topic.getKeywords() + "%' order by t.topic_clickCount desc,t.id ";
	 Page page  = topicService.pagedQueryByHQL(hql, 1, 10, null);
	 List<Topics>  result = (List<Topics>) page.getResult();
	 StringBuffer sb = new StringBuffer();
		for(Topics topic2 : result )
		{
			
			if(topic2.getId().equals(topic.getId()))
				continue;
			sb.append("<li><a href='../"+topic2.getTopic_code()+"/index.html' title='"+topic.getTopic_title()+"' target='_blank'> "+topic2.getTopic_title()+"</a></li>");
		}
		if(sb.length() == 0)
			sb.append("<li>暂无相关记录</li>");
	 return sb.toString();
 }
 
 private String getTop15() throws TuEyeServiceException{
		String hql = " FROM com.tueye.entity.Topics t order   by topic_clickCount desc ";//LIMIT pageNo,pageSize 
		Page page = topicService.pagedQueryByHQL(hql, 1, 12, null);
		List<Topics> topicList = (List<Topics>) page.getResult();
		if(topicList.isEmpty()&&topicList.size()<0){
			return "<li>暂无相关记录</li>";
		}
		StringBuffer sb = new StringBuffer();
		for (Topics topics:topicList) {
			
			sb.append("<li><a href='../"+topics.getTopic_code()+"/index.html' title='"+topics.getTopic_title()+"' target='_blank'> "+topics.getTopic_title()+"</a></li>");        
		}
		
		return sb.toString();
	}
 
 private String getDaoHang(Topics topic){
	 StringBuffer sb = new StringBuffer();
	 sb.append("<a href='../../index.html　title='连接到首页'>首页</a>>>'")
	   .append("<a href='../index.html'>"+topic.getTopic_type().getType_name()+"</a>>>")
	   .append("<a href='#'>").append(topic.getTopic_title()).append("</a>");

	 return sb.toString();
 }
 
 private String getUpNextPage(Topics topic){
	 //查上一篇,本topic 的code大于上一篇，且上一篇按日期倒序
	 String upsql = "select   t.topic_title,t.topic_code from tueye_topics_info t where t.topic_code<" + topic.getTopic_code() +" and t.topic_type_id='"+topic.getTopic_type().getId()+"' order by t.topic_uploaddate desc limit 1";
//	 System.out.println(upsql);
	 //查下一篇，本topic 的code小于下一篇，肯下一篇按日期正序
	 String nextsql = "select t.topic_title,t.topic_code from tueye_topics_info t where t.topic_code>" + topic.getTopic_code() +" and t.topic_type_id='"+topic.getTopic_type().getId()+"'  order by t.topic_uploaddate limit 1";
//	 System.out.println(nextsql);
	 StringBuffer sb = new StringBuffer("上一篇作品:");
	 List uplist = topicService.queryBysql(upsql);
	 List nextlist = topicService.queryBysql(nextsql);
	 if(uplist.size() == 0){
		 sb.append("<a href='../../index.html' title='返回首页'>返回首页</a>");
	 }
	 else{
		 Object[] obj = (Object[]) uplist.get(0);
		 sb.append("<a href='../").append(obj[1]).append("/index.html' title='")
		 .append(obj[0]).append("'>").append(obj[0]).append("</a>");
	 }
	 sb.append("&nbsp;&nbsp;下一篇作品:");
	 if(nextlist.size() == 0){
		 sb.append("<a href='../../index.html' title='返回首页'>返回首页</a>");
	 }else{
		 Object[] obj=(Object[])nextlist.get(0);
		 sb.append("<a href='../").append(obj[1]).append("/index.html' title='")
		 .append(obj[0]).append("'>").append(obj[0]).append("</a>");
	 }
	return sb.toString();
	 
 }
 
}
